package cn.exrick.xboot.modules.oauthLogin;

import cn.exrick.xboot.common.constant.SecurityConstant;
import cn.exrick.xboot.common.vo.TokenUser;
import cn.exrick.xboot.modules.base.service.UserService;
import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.core.userdetails.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class AuthUserPwdController {
    private RequestCache requestCache = new HttpSessionRequestCache();

    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping(value = "/xboot/forwordUrl")
    public void forwordUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {

        log.info("调用重定向，认证授权接口");
        //oauth登录，手动重定向
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        String authToken = null;
        List<String> token = savedRequest.getHeaderValues("authToken");
        if (token.size() == 0){
            String[] tokens = savedRequest.getParameterValues("authToken");
            log.info("savedRequest.getParameterValues的值为" + tokens.toString());
            for (String key: tokens ) {
                authToken = key;
            }
        }else {
            authToken = token.get(0);
        }
        log.info("获取authToken" + authToken);
        String v = redisTemplate.opsForValue().get(SecurityConstant.TOKEN_PRE + authToken);

        TokenUser user = new Gson().fromJson(v, TokenUser.class);

        // 权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 缓存了权限
        for(String ga : user.getPermissions()){
            authorities.add(new SimpleGrantedAuthority(ga));
        }

        org.springframework.security.core.userdetails.User principal = new User(user.getUsername(), "", authorities);

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(principal, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String authUrl = savedRequest.getRedirectUrl();
        authUrl = StrUtil.subBefore(authUrl,"&authToken=",true);
        log.info("auth认证成功后回调地址(清洗掉&authToken=)：" + authUrl);
        response.sendRedirect(authUrl);
    }
}
